const puppeteer = require("puppeteer");
const moment = require("moment");
const getId = require("../../../common/getid");

const {createIPhone, config} = require("../../../common/mobile");
const {
    info,
    saveFile,
    logging,
    reporter,
    pickOne
} = require("../../../common/util");

const name = "orange";
const today = moment().format("YYYY-MM-DD");
const logdir = `./logs/${today}/spain/orange/${info.deviceid}`;

const r = reporter(name);
const logger = logging(name, logdir);

const postData = {
    operator_code: JSON.parse(info.meta).operator_code,
    task_id: "f_sp_orange"
};

async function awaitSelector(m, selector, options, errorTimes, fun) {
    let times = 0;

    while (true) {
        try {
            await m._page.waitForSelector("#btn_continuar", options);
            break;
        } catch (e) {
            times++;
            if (fun) {
                fun(times);
            }
            if (times >= errorTimes) {
                throw e;
            }
        }
    }
}

(async () => {
    let value = await getId(postData);
    value = JSON.parse(value);

    if (value.code !== 0) {
        logger.error("no click id");
        return;
    }

    const links = [
        `http://offer.lpaosub.com/offer/track?of=1102&click=${value.data}&pub={pub_id}`,
        `http://offer.lpaosub.com/offer/track?of=1103&click=${value.data}&pub={pub_id}`
    ];

    const browser = await puppeteer.launch(config);
    const [page] = await browser.pages();

    const m = await createIPhone(page);

    //sub status linstener
    m._page.on("response", response => {
        let url = response.url();
        let status = response.status();

        if (url.startsWith("http")) {
            logger.info(`${response.request().method()}`, status, url);
        }

        if (url.startsWith("http://es.mnt-hk.com/service/sub/result?dcbMsisdn=")) {
            logger.info("success");
            r.s("success");
        }

        if (url.startsWith("http://google.com")) {
            r.w("failure", url);
            m.close();
        }
    });

    //开始
    try {
        r.i("start");

        logger.info("start");

        await m.get(pickOne(links));

        //等待页面加载完成
        await awaitSelector(m, "#btn_continuar", {timeout: 1000}, 3, (times) => {
            logger.info(`第${times}次等待`)
        });
        // await m._page.waitForSelector("#btn_continuar", {timeout: 300000});
        await awaitSelector(m, "#form-confirm", {timeout: 1000}, 3, (times) => {
            logger.info(`第${times}次等待`)
        });
        // await m._page.waitForSelector("#form-confirm", {timeout: 300000});

        //保存页面
        saveFile(`${logdir}/1.html`, await m._page.content());
        logger.info("save1");

        await page.evaluate(async () => {
            Object.defineProperty(navigator, "platform", {get: () => "iphone"});
        });

        await m.tapElement("#btn_continuar");

        await awaitSelector(m, "#popup", {timeout: 1000, visible: true}, 3);
        // await m._page.waitForSelector("#popup", {visible: true});

        await awaitSelector(m, "#btn_popup_der", {timeout: 1000}, 3);
        // await m._page.waitForSelector("#btn_popup_der");
        const btn = await m._page.$("#btn_popup_der");

        let {x, y, width, height} = await btn.boundingBox();

        let mx = parseInt(x + (Math.random() * width) / 2);
        let my = parseInt(y + (Math.random() * height) / 2);

        await m.sleep(60 * 60 * 1000);

        await m.tap(mx, my);

        logger.info("submit");

        await m.sleep(3 * 60 * 1000);

        logger.info("end");
        r.i("end");
    } catch (e) {
        saveFile(`${logdir}/error.html`, await m._page.content());
        r.e(e + "");
        logger.error(e);
    } finally {
        await m.close();
    }
    await browser.close();
})();
